﻿using CanDoo.Admin.Core.Contracts;
using CanDoo.Admin.Core.Identity;
using CanDoo.Core.Context;
using CanDoo.Core.Logging;
using CanDoo.Core.Security;
using CanDoo.Data;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Oil.Core.DTOs;
using CanDoo.Oil.WebApi.Api.Results;
using CanDoo.Oil.WebApi.Areas.Api.Filters;
using Microsoft.Owin.Security;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace CanDoo.Oil.WebHost.Areas.Api.Controllers
{
    [TinderApiExceptionFilterAttribute]
    [TinderValidationActionFilter]
    [Description("单据入库webapi接口")]
    [RoutePrefix("api/order")]
    public class OrderController : ApiController
    {
        #region owin

        public IAuthenticationManager AuthenticationManager { get; private set; }//认证管理
        public SignInManager SignInManager { get; private set; }//登陆管理

        #endregion

        #region Manager

        public IPermissionManager PermissionManager { get; private set; }
        public IOperateLoger OperateLoger { get; set; }
        public IOperator Operator { get; set; }

        /// <summary>
        /// 售油机序列号
        /// </summary>
        public IOilSalesSerialNumContract OilSalesSerialNumContract { get; set; }
        public ICustomerContract CustomerContract { get; set; }//客户管理
        public IUserContract UserContract { get; set; }//用户管理

        /// <summary>
        /// Api操作日志
        /// </summary>
        public IAPIOperateLogContract APIOperateLogContract { get; set; }
        public IStoreActivityContract StoreActivityContract { get; set; }

        public IProductContract ProductContract { get; set; }

        /// <summary>
        /// 取油吗
        /// </summary>
        public IGetOilCodeContract GetOilCodeContract { get; set; }

        public IOilSerialNumContract OilSerialNumContract { get; set; }

        public IMediaADContract MediaADContract { get; set; }

        #endregion

        #region 属性

        private string _PageCode;
        public string PageCode
        {
            get
            {
                if (string.IsNullOrEmpty(_PageCode))
                {
                    _PageCode = this.GetType().Name;
                }
                return _PageCode;
            }
        }

        private string _pageTitle;
        public string PageTitle
        {
            get
            {
                if (string.IsNullOrEmpty(_pageTitle))
                {
                    _pageTitle = this.GetType().ToDescription();
                }
                return _pageTitle;
            }
        }

        #endregion

        
        public IOrderApiContract OrderApiContract { get; set; }

        #region ctor

        public OrderController(IAuthenticationManager authenticationManager
            , SignInManager signInManager
            , IPermissionManager permissionManager
            )
        {
            AuthenticationManager = authenticationManager;
            SignInManager = signInManager;
            PermissionManager = permissionManager;

            PermissionManager.PageCode = PageCode;
            PermissionManager.PageTitle = PageTitle;
        }

        #endregion

        // GET api/<controller>
        //public IEnumerable<OrderApiDto> Get()
        //{
        //    var data = OrderApiContract.Get();
        //    return new List<OrderApiDto>();
        //}

        // GET api/<controller>/5
        //public async Task<HttpResponseMessage> Get(string id)
        //{
        //    if (id == null)
        //        throw new ArgumentException(nameof(id) + "不能为空");

        //    OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo();
        //    OperateLoger.InputMessage = JsonConvert.SerializeObject(id);



        //    OrderApiDto order = OrderApiContract.Get();



        //    OperateLoger.OperationResult = OperationResult.Success;

        //    var result = new ApiResult<OrderApiDto>();
        //    OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
        //    await OperateLoger.SaveLogAsync();

        //    result.Data = order;
        //    OperationResult or = new OperationResult(OperationResultType.Success);
        //    if (or.Succeeded)
        //    {
        //        result.ResultType = ApiResultCode.sucess;
        //    }
        //    else
        //    {
        //        result.ResultType = ApiResultCode.fail;
        //    }
        //    result.InnerMessage = or.Message;
        //    return Request.CreateResponse(or.Succeeded ? HttpStatusCode.OK : HttpStatusCode.BadRequest, result);
        //}

        [Route("Read")]
        [Display(Name = "获取单据信息")]
        [HttpPost]
        // GET api/<controller>/5
        public async Task<HttpResponseMessage> Read(OrderApiDtoKey orderKey)
        {
            if (orderKey == null)
                throw new ArgumentNullException(nameof(orderKey) + "不能为空");

            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "Read", pagecode: this.PageCode, powerName: "获取单据信息", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(orderKey);


            string oid = orderKey.oId;

            OrderApiDto order = OrderApiContract.GetByOrderNo(oid);
            
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult<OrderApiDto>();
            
            result.Data = order;
            OperationResult or = new OperationResult(OperationResultType.Success);
            if (or.Succeeded)
            {
                result.ResultType = ApiResultType.sucess;
            }
            else
            {
                result.ResultType = ApiResultType.fail;
            }
            result.Message = or.Message;
            result.InnerMessage = or.Message;

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            await OperateLoger.SaveLogAsync();

            return Request.CreateResponse(or.Succeeded ? HttpStatusCode.OK : HttpStatusCode.OK, result);
        }

        [Route("Save")]
        [Display(Name = "保存单据信息")]
        [HttpPost]
        // GET api/<controller>/5
        public async Task<HttpResponseMessage> Save(OrderApiDto value)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "Save", pagecode: this.PageCode, powerName: "保存单据信息", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(value);
            
            var or = OrderApiContract.Save(value);
            
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult();

            

            if (or.Succeeded)
            {
                result.ResultType = ApiResultType.sucess;
            }
            else
            {
                result.ResultType = ApiResultType.fail;
            }
            result.Message = or.Message;
            result.InnerMessage = or.Message;
            result.Data = or.Data;

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            await OperateLoger.SaveLogAsync();

            return Request.CreateResponse(or.Succeeded ? HttpStatusCode.OK : HttpStatusCode.OK, result);
        }

        // POST api/<controller>
        public OrderApiDto Post([FromBody]OrderApiDto value)
        {
            return value;
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}